//
//  ViolationListController.swift
//  TrafficViolation
//
//  Created by eaglelive on 2017/5/4.
//  Copyright © 2017年 eaglelive. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class ViolationListController: BaseController {
    
    var carid : String = ""
    var carnum : String = ""
    var isSelf:Int = 1//默认本人
    var violationTable:UITableView!//数据表格
    var totalcount:Int = 0//选中总条数
    var violationArray:[ViolationModel]!
    var submitArray:[Any]!//
    var idStrArray:[String]!
    var totalPrice = "0"
    var totalCount = "0"
    var vListCell:ViolationCell!
    lazy var bottomView: ViolationListBottom = {
        let view = ViolationListBottom(frame: CGRect(x: 0, y: kScreenH - kTabBarH, width: kScreenW, height: kTabBarH))
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setupNavBar(title: carnum, isback: true, appearWay: 3, isright: false)//自定义导航
        violationArray = Array<ViolationModel>()
        idStrArray = Array<String>()//取消的违章id
        submitArray = Array<Any>()
        loadViolationList()
        //初始化表格
        violationTable = UITableView(frame: CGRect(x:0,y:kStatusBarH + kNavigationBarH,width:kScreenW,height:kScreenH),style: UITableViewStyle.plain)
        violationTable.delegate = self
        violationTable.dataSource = self
        violationTable.backgroundColor = tableBgColor
        violationTable.separatorStyle = UITableViewCellSeparatorStyle.none
        violationTable.rowHeight = 115
        violationTable.tag = 1
        self.view.addSubview(violationTable)
        violationTable.snp.makeConstraints({ (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(kStatusBarH + kNavigationBarH)//选项卡高度 40
            make.bottom.equalTo(self.view).offset(-kTabBarH)
        })
        self.view.addSubview(self.bottomView)
    }
}
extension ViolationListController{
    func choseSubmitElement(){
        if idStrArray.count == 0{
            for (_,value) in violationArray.enumerated() {
                let model =  value as ViolationModel
                if "1" == model.status{
                    continue
                }else{
                    let params: NSMutableDictionary = NSMutableDictionary()
                    params["vioID"] = "\(model.vioID)"
                    params["samount"] = "\(model.samount)"
                    self.submitArray.append(params)
                }
            }
        }else{
            for (_,value) in violationArray.enumerated() {
                let model =  value as ViolationModel
                if idStrArray.contains(model.vioID) || "1" == model.status{//取消得和已经提交过的过滤掉
                    continue
                }else {
                    let params: NSMutableDictionary = NSMutableDictionary()
                    params["vioID"] = "\(model.vioID)"
                    params["samount"] = "\(model.samount)"
                    self.submitArray.append(params)
                }
            }
        }
    }
    //提交订单
    func submitBtnClick(sender:UIButton) {
        choseSubmitElement()
        if submitArray.count > 0 {
            let urlString = "\(projectUrl)/order/car/commit/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)" //网络请求地址
            let parameter: Parameters = [
                "carNum":carnum,
                "isSelf":isSelf,
                "detailList":submitArray
            ]
            Alamofire.request(urlString, method: .post, parameters: parameter,encoding: JSONEncoding.default, headers : headers).responseJSON { (response) in
                    if response.result.isSuccess{
                        let json = JSON(response.result.value as! [String : AnyObject])
                        if json["success"] == true {
                            let vsc = ViolationSubmitController()
                            vsc.orderID = json["rdata"].rawString()!
                            self.present(vsc, animated: true, completion: nil)
                        }
                        else{
                            NSLog("提交订单出错啦!\(json["rdata"])")
                            self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                        }
                    }
                    else{
                        print(response.result.error!) //输出错误日志
                    }
                }
        }else{
            let alertController = UIAlertController(title: alertTitle, message: "您没有选择违章信息！", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            alertController.addAction(cancelAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
    //查询违章
    func loadViolationList() {
        let urlString = "\(projectUrl)/car/getCarViolationList/\(carid)/\(userID!)?tokenID=\(tokenID!)&tokenUserID=\(userID!)"
        Alamofire.request(urlString, method: .get, parameters: nil, headers : headers).responseJSON { (response) in
            if response.result.isSuccess{
                let json = JSON(response.result.value as! [String : AnyObject])
                 print("json:\(json)")
                if json["success"] == true {
                    if json["rdata"]["list"].exists() {
                        for (_,subJson) : (String,JSON) in json["rdata"]["list"] {
                            let model = ViolationModel.init(dic: subJson)
                            self.violationArray.append(model)
                        }
                        if self.violationArray.count > 0 { //如果存在
                            self.violationTable.reloadData()
                        }
                        if self.idStrArray.count == 0 {
                            self.totalPrice = json["rdata"]["totalprice"].rawString()!
                            self.totalCount = json["rdata"]["count"].rawString()!
                            self.bottomView.amountLabel.text = String(describing: CGFloat(Double(self.totalPrice)!))
                            self.bottomView.checkedCount.text = self.totalCount
                        }
                    }else{
                        self.bottomView.state = 0 //没有违章数据
                        self.bottomView.amountLabel.text = "0.0"
                        self.bottomView.checkedCount.text = "0"
                        let uiLabel = UILabel(frame: CGRect(x: 25, y: 0, width: kScreenW - 50, height: kScreenH))
                        uiLabel.font = UIFont.systemFont(ofSize: 12)
                        uiLabel.numberOfLines = 0
                        uiLabel.textColor = UIColor.gray
                        uiLabel.textAlignment = .center
                        uiLabel.text = "恭喜您，未查到相关违章记录，继续保持中国好司机的行车习惯。"
                        self.view.addSubview(uiLabel)
                    }
                }
                else{
                    NSLog("获取车辆违章信息出错啦!\(json["rdata"])")
                    self.failOperNoticeFun(code: json["rcode"].rawString()!, message: json["rdata"].rawString()!)
                }
            }
            else{
                print(response.result.error!) //输出错误日志
            }
        }
    }
    func checkClick(sender:UIButton) {
        let model = self.violationArray[sender.tag]
        if sender.isSelected {
            sender.isSelected = false
            totalCount =  String(Int(totalCount)! - 1)
            totalPrice = String(describing: CGFloat(Double(totalPrice)!) - CGFloat(Double(model.price)!) - CGFloat(Double(model.samount)!))
            idStrArray.append(model.vioID)
        }else{
            sender.isSelected = true
            totalCount = String(Int(totalCount)! + 1)
            totalPrice = String(describing: CGFloat(Double(totalPrice)!) + CGFloat(Double(model.price)!) + CGFloat(Double(model.samount)!))
            if idStrArray.count > 0 {
                for (index,value) in idStrArray.enumerated() {
                    if value == model.vioID {
                        idStrArray.remove(at: index)
                        break
                    }
                }
            }
        }
        print("totalCount:\(totalCount),totalPrice:\(totalPrice),indexArray:\(idStrArray)")
        self.bottomView.amountLabel.text = totalPrice
        self.bottomView.checkedCount.text = totalCount
    }
}
extension ViolationListController:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.violationArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        vListCell = tableView.dequeueReusableCell(withIdentifier: "violationCellID") as? ViolationCell
        if vListCell == nil {
            vListCell = ViolationCell(style: UITableViewCellStyle.default,reuseIdentifier: "violationCellID")
        }
        if self.violationArray.count > 0 {
            let index = indexPath.row
            let model = violationArray[index]
            vListCell.checkBox.tag = index
            if "0" == model.status {
                vListCell.violationState.text = "未处理"
                vListCell.checkBox.isSelected = true
                vListCell.checkBox.isEnabled = true
                vListCell.checkBox.addTarget(self, action: #selector(checkClick(sender:)), for: UIControlEvents.touchUpInside)
            }
            if "1" == model.status {
                vListCell.violationState.text = "处理中"
                vListCell.checkBox.isSelected = false
                vListCell.checkBox.isEnabled = false
            }
            if idStrArray.count > 0 {
                if idStrArray.contains(model.vioID) {
                    vListCell.checkBox.isSelected = false
                }
            }
            vListCell.configCellDateWithModel(model:model)
        }
        return vListCell
    }
    //选中cell时触发这个代理
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        let vic = ViolationInfoController()
        vic.violation = violationArray[(indexPath as NSIndexPath).row]
        self.present(vic, animated: true, completion: nil)
    }
}
